package net.sevear.chaos.download
{
	import com.adobe.serialization.json.JSON;
	
	import flash.events.Event;
	import flash.net.URLRequest;
	
	import net.sevear.chaos.event.SourceProxyEvent;

	public class SinaYuekuProxy extends GoogleMusicProxy
	{
		public function SinaYuekuProxy()
		{
			super(DBRadioKeeper.SOURCE_SINA);
		}
		
		override protected function initURLs():void{
			SEARCH_URL = "http://music.sina.com.cn/yueku/search/s.php?e=utf-8&t=all&k=%s&p=%d&l=%d";
			GET_SONG_INFO_URL = "http://music.sina.com.cn/services/sina.music.get.song.info.php?songid=";
		}
		
		override protected function onComplete(e:Event=null):void{
			var rstStr:String = loader.data as String;
			switch(stepIdx){
				case GETTING_SEARCH_RST:
					handleHtmlRst(rstStr);
					break;
				case GETTING_SONG_INFO:
					handleSongInfo(rstStr);
					break;
				case GETTING_MP3_URL:
					var url:String = rstStr.substr('iask_music_song_url="'.length,rstStr.length-'iask_music_song_url="'.length-2);
					dispatchEvent(new SourceProxyEvent(SourceProxyEvent.FOUND_URL,url,this.sourceType));
					timer.stop();
					break;
			}
		}
		
		private function handleHtmlRst(rstStr:String,nextFindFunc:Function = null):void{
			var songs:Array;
			songs = parseRst(rstStr);
			if(songs.length>0){
				var hitSong:Object = selectFittestSong(songs);
				if(hitSong!=null){
					getSongInfo(hitSong.id as int);
				}else{
					dispatchEvent(new SourceProxyEvent(SourceProxyEvent.NOT_FOUND_URL));
					timer.stop();
				}
			}else{
				if(nextFindFunc!=null){
					nextFindFunc();
				}else{
					dispatchEvent(new SourceProxyEvent(SourceProxyEvent.NOT_FOUND_URL));
					timer.stop();
				}
			}
		}
		
		private function selectFittestSong(songs:Array):Object{
			var songList:Array = [];
			var highestPoint:int;
			var highestSong:Object;
			for each (var song:Object in songs) {
				var point:int = getMatchPoint(curtrack.name,song.name.toString());
				if(point<=0) continue;
				var artistPoint:int = getMatchPoint(curtrack.artistName,song.artist.toString());
				if(artistPoint<=0){
					continue;
				}else point +=artistPoint;
				var albumPoint:int =getMatchPoint(curtrack.albumName,song.album.toString());
				if(point>highestPoint){
					highestPoint = point;
					highestSong = song;
				}
				if(highestPoint == FULL_MATCH*3){
					break;
				}
			}    
			return highestSong;
		}
		
		
		private function getSongInfo(songId:int):void{
			stepIdx = GETTING_SONG_INFO;
			var url:String = GET_SONG_INFO_URL+songId;
			loader.load(new URLRequest(encodeURI(url)));
		}
		
		
		private function handleSongInfo(rstStr:String):void{
			var _songInfos:Array=new Array();
			var jsonStr:String = rstStr.substr('varname='.length,rstStr.length-'varname='.length);
			try{
				var jsonObj:Object = JSON.decode(jsonStr);
				if(jsonObj!=null){
					var sonInfo:Object = (jsonObj.data as Array).length>0?jsonObj.data[0]:null;
					if(sonInfo!=null){
						stepIdx = GETTING_MP3_URL;
						var iaskUrl:String = sonInfo.IASKURL as String;
						loader.load(new URLRequest(encodeURI(iaskUrl)));
					}else{
						dispatchEvent(new SourceProxyEvent(SourceProxyEvent.SERVICE_BREAK_DOWN));
						timer.stop();
					}
				}
			}catch(e:Error){
				timer.stop();
				dispatchEvent(new SourceProxyEvent(SourceProxyEvent.SERVICE_BREAK_DOWN));
				trace(e.message);
			}
			
		}
		
		private function parseRst(html:String):Array{
			html = html.substr(html.search(/<!--正文开始-->/)+'<!--正文开始-->'.length,
				html.search(/<!--正文结束-->/));
			
			var divs:Array = html.split('<div class="gqlb_con" onMouseOver="search_2009.s_op_s($(this)');
			var items:Array = [];
			if(divs!=null ) {
				trace("Sina search total results :",divs.length);
				for each(var divStr:String in divs){
					if(divStr.search(/<span style="color:red">/)<0) continue;
					else{
						var songSIdx:int = divStr.search(/<li class="li_03[\d_ a-z]*">/);
						var artistSIdx:int = divStr.search(/<li class="li_04[\d_ a-z]*">/);
						var albumSIdx:int = divStr.search(/<li class="li_05[\d_ a-z]*">/);
						if(songSIdx<=0 || artistSIdx<=0 || albumSIdx<=0){
							continue;
						}else{
							//<div class="left hi"><a onclick="mpwPlay([\d]+);" href="javascript:;" title="[^"]*">
							var rstSongArr:Array = divStr.match(/<div class="left hi"><a onclick="mpwPlay\([\d]+\);" href="javascript:;" title="[^"]*">/);
							if(rstSongArr==null || rstSongArr.length<=0){
								continue;
							}else{
								var rstSongIdStr:String = (rstSongArr[0] as String).slice('/<div class="left hi"><a onclick="mpwPlay('.length-1,
									(rstSongArr[0] as String).search(/\)/));
								var rstSongId:int = parseInt(rstSongIdStr);
								var rstSong:String =  (rstSongArr[0] as String).slice('<div class="left hi"><a onclick="mpwPlay();" href="javascript:;" title="'.length+rstSongIdStr.length,
									(rstSongArr[0] as String).length-2);
								
								rstSongArr = divStr.match(/<li class="li_04[\d_ a-z]*"><a target="_blank" href="http:\/\/music\.sina\.com\.cn\/yueku\/s\/[\d]+.html" title="[^"]*">/);
								var rstArtist:String = rstSongArr[0] as String;
								rstArtist = rstArtist.slice(rstArtist.search(/title="/)+'title="'.length,rstArtist.length-2);
								rstSongArr = divStr.match(/<li class="li_05[\d_ a-z]*"><a target="_blank" href="http:\/\/music\.sina\.com\.cn\/yueku\/a\/[\d]+.html" title="[^"]*">/);
								var rstAlbum:String = rstSongArr[0] as String;
								rstAlbum = rstAlbum.slice(rstAlbum.search(/title="/)+'title="'.length,rstAlbum.length-2);
								
								var song:Object = new Object();
								song.id = rstSongId;
								song.name = rstSong;
								song.artist = rstArtist;
								song.album = rstAlbum;
								items.push(song);
							}
						}
					}
				}
			}
			return items;
		}
	}
}